#!/usr/local/bin/python
#-*- coding:utf-8 -*-
#接口类型：互亿无线触发短信接口，支持发送验证码短信、订单通知短信等。
#账户注册：请通过该地址开通账户http://sms.ihuyi.com/register.html
#注意事项：
#（1）调试期间，请用默认的模板进行测试，默认模板详见接口文档；
#（2）请使用APIID（查看APIID请登录用户中心->验证码短信->产品总览->APIID）及 APIkey来调用接口；
#（3）该代码仅供接入互亿无线短信接口参考使用，客户可根据实际需要自行编写；

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from live_api.tools.Output_Helper import *

import httplib
import urllib,random,string,json
from live_api.tools.constant import datais
from live_api.tools.Redis_Driver import rds

host  = "106.ihuyi.com"
sms_send_uri = "/webservice/sms.php?method=Submit"

#用户名是登录用户中心->验证码短信->产品总览->APIID
account  = datais.APIID
#密码 查看密码请登录用户中心->验证码短信->产品总览->APIKEY
password = datais.APIKEY

def send_sms(text, mobile):
    params = urllib.urlencode({'account': account, 'password' : password, 'content': text, 'mobile':mobile,'format':'json' })
    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
    conn = httplib.HTTPConnection(host, port=80, timeout=30)
    conn.request("POST", sms_send_uri, params, headers)
    response = conn.getresponse()
    response_str = response.read()
    conn.close()
    return response_str

import DB_Driver as DB

# def sendSmsCode(mobile):
#     db = DB.getDB()
#     print mobile
#     sql = 'select * from message where cname=%s'% (mobile)
#     n = db.execute(sql)
#
#     code=rds.get(mobile)
#     print 'code111111', code
#     # print mobile
#     if code==None:
#         code=''.join(random.sample(string.digits, 6))
#         print 'code22222222', code
#         rds.set(mobile,code)
#         rds.expire(mobile,30)
#
#     else:
#         rds.expire(mobile,30)
#     text = "您的验证码是：%s。请不要把验证码泄露给其他人。"% code
#     print 'text', text
#     response_str=send_sms(text, mobile)
#     print 'response_str', response_str
#     return json.loads(response_str)


def sendSmsCode(mobile):
    db = DB.getDB()
    print mobile
    sql = 'select * from message where cname=%s' % (mobile)
    n, rows = db.query(sql)
    count = 1
    code = ''.join(random.sample(string.digits, 6))
    if n == 0:
        id = maxid('message', 'id')
        sql = "insert into message(id,cname,content,cdate) values(%s,%s,%s,%s)" % (id,mobile,count,code)
        # print sql
        db.execute(sql)
    else:
        sql = "update message set cdate='%s' where cname='%s'" % (code,mobile)
        # print sql
        db.execute(sql)
    text = "您的验证码是：%s。请不要把验证码泄露给其他人。" % code
    # print 'text', text
    response_str = send_sms(text, mobile)
    # print 'response_str', response_str
    return json.loads(response_str)




def verifycode(mobile,code_par):
    db = DB.getDB()
    sql = 'select * from message where cname=%s' % (mobile)
    n, rows = db.query(sql)
    if not n:
        rows = ({'cdate':111111},)
    if int(rows[0]['cdate'])==int(code_par) or int(rows[0]['cdate']) == int(code_par):
        response_str={"code":200,"msg":"验证成功"}
    elif n == 0:
        response_str={"code":1003,"msg":"验证码错误"}
    return response_str

if __name__ == '__main__':

    mobile = "138xxxxxxxx"
    text = "您的验证码是：121254。请不要把验证码泄露给其他人。"

    # print(send_sms(text, mobile))